// 声明类
let that
class Tabs {
    constructor(id){
        //获取tab盒子(父级)
        that = this
     this.main = document.querySelector(id)
     
     this.addBtn = this.main.querySelector('.tabadd')
     
     this.ul = this.main.querySelector('.fisrstnav ul')
     this.sectionFather = this.main.querySelector('.tabscon')
     this.init()
    }

    init() {
        this.updata()
        this.lis.forEach((item,index)=>{
            item.index =index
            item.addEventListener('click',this.toggleTabs)
        })
        this.addBtn.addEventListener('click',this.addTabs)
        this.delbtns.forEach(item=>{
            item.addEventListener('click',this.delTabs)
        })
        this.spans.forEach(item=>{
            item.addEventListener('dblclick',this.editTabs)
        })
        this.sections.forEach(item=>{
            item.addEventListener('dblclick',this.editTabs)
        })
    }

    updata(){
        this.lis = this.main.querySelectorAll('li')
        this.sections = this.main.querySelectorAll('section')
        this.delbtns = this.main.querySelectorAll('.fisrstnav .iconfont')
        this.spans =this.main.querySelectorAll('.fisrstnav li span:first-child')
    }

    clearClassName(){
     this.lis.forEach(item=>{
       item.classList ='' 
     })
     this.sections.forEach(item=>{
        item.classList ='' 
      })
    }

    toggleTabs(){
     that.clearClassName()
     this.classList ='liactive'
    //  console.log(this.index);
     that.sections[this.index].classList ='conactive'
    }

    addTabs(){
        // console.log(1);
        that.clearClassName()
    const li =` <li class="liactive"><span>测试1</span><span class="iconfont icon-guanbi"></span></li>`
    const section =`<section class="conactive">${Math.random()}</section>`
    that.ul.insertAdjacentHTML('beforeend',li)
    that.sectionFather.insertAdjacentHTML('beforeend',section)
    that.init()
}
    delTabs(e){
     // console.log('删除');
     let index =this.parentNode.index
     e.stopPropagation()
     this.parentNode.remove()
     that.sections[index].remove() 
     that.init()
     if(that.main.querySelector('.liactive'))return 
     index
     ?that.lis[index-1]&&that.lis[index-1].click()
     :that.lis[index]&&that.lis[index].click()
     
     }

    editTabs(){
        window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
        const str =this.innerHTML
        // console.log(this);
        this.innerHTML  =  `<input type="text">`
        // console.log(this.children[0]);
        const input = this.children[0]
        input.value = str
        input.select()
        input.onblur =function(){
            this.parentNode.innerHTML = this.value
        }
        input.onkeyup=function(e){
           if(e.keyCode===13) this.blur()
        }
     }
}
// 实例化对象(绑定点击事件)
new Tabs('#tab')

